import React, { Component } from 'react'
import { connect } from 'react-redux'
import axios from '../../http'
import { SET_LIST } from '../../store/actions/list'
import { ADD_ITEM } from '../../store/actions/car'
import { Toast } from 'antd-mobile'
import './Classify.css'

export class Classify extends Component {
    render() {
        const { list, addItem } = this.props
        return (
            <div>
                {
                    list.map(item => {
                        return <div className='classify_box' key={item.id}>
                            <div className='img_box'>
                                <img style={{
                                    width: "80px",
                                    height: "80px"
                                }} src={item.img} alt="" />
                            </div>
                            <div className='price_box'>
                                <h4>
                                    { item.title }
                                </h4>
                                <p>
                                    { item.price }
                                    <button onClick = { () => {
                                        addItem(item)
                                    }} className='btn'> ++ </button>
                                </p>
                            </div>
                        </div>
                    })
                }
            </div>
        )
    }
    componentDidMount() {
        this.props.init()
    }
}

const mapStateToProps = (state) => {
    const { list } = state
    return {
        list
    }
}

const mapDispatchToProps = (dispatch) => {
    return {
        init() {
            dispatch(async (next) => {
                let res = await axios.get('/getList')
                next({ type: SET_LIST, res })
            })
        },
        addItem(item) {
            dispatch({ type: ADD_ITEM, item })
            Toast.success(item.title + '添加成功')
        }
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(Classify)
